package com.liuqi.aiagent.service.impl;

import com.liuqi.aiagent.mapper.AgentEventMapper;
import com.liuqi.aiagent.service.AgentEventService;
import com.liuqi.aiagent.transfer.entity.AgentEvent;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author liuqi
 * @date 2025/7/17
 **/
@Service
@AllArgsConstructor
@Slf4j
public class AgentEventServiceImpl implements AgentEventService {

    private AgentEventMapper agentEventMapper;

    @Override
    public void modelEditEvent(int modelId) {
        List<Integer> agentIds = agentEventMapper.findAgentIdByModelId(modelId);
        saveBatch(agentIds, "模型");
    }

    @Override
    public void webhookToolEditEvent(List<Integer> toolIds, String toolType) {
        log.info("发布Agent的[工具变更]事件");
        List<Integer> agentIds = agentEventMapper.findAgentIdByToolIds(toolIds, toolType);
        saveBatch(agentIds, "工具");
    }

    private void saveBatch(List<Integer> agentIds, String eventName) {
        if (agentIds.isEmpty()) {
            return;
        }
        log.info("发布Agent的[" + eventName + "编辑]事件. agentIds: " + agentIds);
        List<AgentEvent> agentEvents = new ArrayList<>(agentIds.size());
        agentIds.forEach(agentId -> {
            agentEvents.add(new AgentEvent(agentId, "【" + eventName + "】发生变更, 需要发布更新"));
        });
        agentEventMapper.saveBatch(agentEvents);
    }

}
